const path = require("path");

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");

// The path to the ceisum source code
const cesiumSource = "node_modules/cesium/Source";
const cesiumWorkers = "../Build/Cesium/Workers";

// const CesiumDebugDir = "node_modules/cesium/Build/Cesium";
// const CesiumReleaseDir = "node_modules/cesium/Source";

module.exports = {
  baseUrl: "proj_no_1",
  configureWebpack: {
    resolve: {
      alias: {
        // Cesium module name
        cesium: path.resolve(__dirname, cesiumSource) // 用source会导致每次build所有cesium js；用DebugDir，则存在widgets.css引用问题
      }
    },
    // externals: {
    //   cesium: "cesium/Cesium"
    // },
    amd: {
      // Enable webpack-friendly use of require in cesium
      toUrlUndefined: true
    },
    module: {
      rules: [
        {
          test: require.resolve("cesium-heatmap"),
          use: "exports-loader?CesiumHeatmap"
        }
        // {
        //   test: require.resolve('heatmap.js'),
        //   use: 'exports-loader?h337'
        // }
      ]
    },
    plugins: [
      new webpack.DefinePlugin({
        // Define relative base path in cesium for loading assets
        CESIUM_BASE_URL: JSON.stringify("")
      }),

      // Copy Cesium Assets, Widgets, and Workers to a static directory
      // 对build生效，拷贝到dist目录下。如：dist/Assets
      new CopyWebpackPlugin([
        {
          from: path.join(cesiumSource, cesiumWorkers),
          to: "Workers"
        }
      ]),
      new CopyWebpackPlugin([
        {
          from: path.join(cesiumSource, "Assets"),
          to: "Assets"
        }
      ]),
      new CopyWebpackPlugin([
        {
          from: path.join(cesiumSource, "Widgets"),
          to: "Widgets"
        }
      ]),
      new webpack.ProvidePlugin({
        Cesium: ["cesium/Cesium"], // Cesium对象实例可在每个js中使用而无须import
        // Cesium: ["cesium/Build/Cesium/Cesium.js"]
        // cesium/Build/Cesium/Cesium.js
        // CesiumHeatmap: 'cesium-heatmap'
        h337: "heatmap.js/build/heatmap.js" // h337对象实例在每个js可用
      })
    ],
    optimization: {
      minimize: process.env.NODE_ENV === "production" ? true : false
    }
  }
};

if (process.env.NODE_ENV === "production") {
  module.exports.configureWebpack.devtool = false; // 不生成source map
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.configureWebpack.plugins = (module.exports.configureWebpack.plugins || []).concat([
    new CleanWebpackPlugin(),

    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ]);
} else {
  module.exports.configureWebpack.devtool = "#source-map";
}
